#import "MainViewController.h"
#import "collectionCell.h"
#import "WXViewController.h"
#import "WeixListViewController.h"
#import "YpViewController.h"
#import "WyHomeListViewController.h"
#import "TongzhiListViewController.h"
#import "TongzhiViewController.h"
#import "GrzlViewController.h"
#import "Reg3ViewController.h"
#import "SDCycleScrollView.h"
#import "WyHomeViewController.h"
#import "UIImageView+WebCache.h"
#import "PipeiViewController.h"
#import "MenuViewController.h"
#import "DemoTableViewControler.h"
#import "KhzlViewController.h"
#import <QuartzCore/QuartzCore.h>

@interface MainViewController (){
    UserInfo *user;
}
@property (nonatomic, strong) NetworkManager *networkManager;
@property (nonatomic, strong) MBProgressHUD *HUD;
@property (nonatomic, strong) NSMutableArray* ids;
@property (nonatomic, strong) NSMutableArray* type;
@property (nonatomic, strong) NSMutableArray *tzList;

@end

#define kStoreAppId  @"1035160573"  // （appid数字串）

@implementation MainViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.navigationController setNavigationBarHidden:YES];
    user = [UserInfo instance];
    [self setUpCollection];
    [self loadWeather];
    
    
    self.tzList = [NSMutableArray array];
    NSString *stringAll =@"";
    NSString *nickname = [user.info objectForKey:@"nickname"] ;
    
    if(nickname == nil || [@"" isEqualToString:nickname]){
        self.nameText.text = [[user.info objectForKey:@"username"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    } else {
        self.nameText.text = [nickname stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }
    if([user.info objectForKey:@"touxiang"]){
        
        NSString *image1Str = [NSString stringWithFormat:@"%@%@",SERVER_PATH,[user.info valueForKey:@"touxiang"]];
        NSURL *url1 = [NSURL URLWithString:image1Str];
        [_touxiangImage sd_setImageWithURL:url1];
        
        
        SDWebImageManager *manager = [SDWebImageManager sharedManager];
        [manager downloadImageWithURL:url1 options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {
            
        } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
        }];
    } else {
        [_touxiangImage setImage:[UIImage imageNamed:@"Icon.png"]];
    }
    
    self.xiaoquText.text = stringAll;
    //    }
    if (self.networkManager == nil) {
        self.networkManager = [[NetworkManager alloc] init];
    }
    NSString *xiaoqu_id = @"8";
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           xiaoqu_id,@"xiaoqu_id", nil];
    [self.networkManager requestWithMethod:zhiding parameter:param delegate:self];
    [self.HUD show:YES];
    
   
    
}

- (void)viewDidAppear:(BOOL)animated{
    if([user.info objectForKey:@"touxiang"]){
        
        NSString *image1Str = [NSString stringWithFormat:@"%@%@",SERVER_PATH,[user.info valueForKey:@"touxiang"]];
        NSURL *url1 = [NSURL URLWithString:image1Str];
        [_touxiangImage sd_setImageWithURL:url1];
        
        
        SDWebImageManager *manager = [SDWebImageManager sharedManager];
        [manager downloadImageWithURL:url1 options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {
            
        } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
        }];
    } else {
        [_touxiangImage setImage:[UIImage imageNamed:@"Icon.png"]];
    }
}

//收集设备信息
- (void)sendDeviceInfo {
    NSString *user_id = [user.info objectForKey:@"user_id"];
    
    NSString *pushId = @"";
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults valueForKey:@"token"]) {
        pushId = [defaults valueForKey:@"token"];
    }
    NSString *systemVersion = [UIDevice currentDevice].systemVersion;
    NSString *systemOS = [NSString stringWithFormat:@"IOS%@",systemVersion];
    
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           pushId,@"pushId",
                           systemOS,@"systemOS",
                           user_id,@"userId",
                           nil];
    [self.networkManager requestWithMethod:sendDeviceInfo parameter:param delegate:nil];
    
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 1000) {
    } else if (alertView.tag == 1001) {
        if (buttonIndex == alertView.firstOtherButtonIndex) {
            NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://itunes.apple.com/us/app/id%@?ls=1&mt=8", kStoreAppId]];
            [[UIApplication sharedApplication] openURL:url];
        }
    }
}


- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFinishedWithResult:(id)data {
    [self.HUD hide:YES];
    
    if (methodId == zhiding) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            NSString * result = [data objectForKeyOrNil:@"result"];
            
            if([result isEqualToString:@"000"]){
                NSArray *results = [data objectForKeyOrNil:@"zhidingList"];
                NSMutableArray* titles = [[NSMutableArray alloc] init];
                _ids = [[NSMutableArray alloc] init];
                _type = [[NSMutableArray alloc] init];
                NSMutableArray* imagesURLStrings = [[NSMutableArray alloc] init];
                
                if (![results isKindOfClass:[NSNull class]] && [results count] > 0) {
                    [self.tzList  addObjectsFromArray:results];
                    for(int i=0;i<[results count];i++){
                        NSMutableDictionary *str = [results objectAtIndex:i];
                        [titles addObject:[[str objectForKey:@"title"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
                        [imagesURLStrings addObject:@"beijing1.jpg"];
                        [_ids addObject:[str objectForKey:@"id"]];
                        [_type addObject:[str objectForKey:@"type"]];
                    }
                    
                    CGFloat w = self.view.bounds.size.width;
                    //网络加载 --- 创建带标题的图片轮播器
                    SDCycleScrollView *cycleScrollView2 = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 180, w, 55) imageURLStringsGroup:nil]; // 模拟网络延时情景
                    cycleScrollView2.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
                    cycleScrollView2.delegate = self;
                    cycleScrollView2.titlesGroup = titles;
                    //                    cycleScrollView2.dotColor = [UIColor grayColor]; // 自定义分页控件小圆标颜色
                    cycleScrollView2.placeholderImage = [UIImage imageNamed:@"placeholder"];
                    [self.view addSubview:cycleScrollView2];
                    //             --- 模拟加载延迟
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        cycleScrollView2.imageURLStringsGroup = imagesURLStrings;
                    });
                }
            }
        }
        
    } else if (methodId == getUnreadCount) {
        self.dataMArr = [NSMutableArray array];
        
        NSString *user_type = [user.info objectForKey:@"roleName"];
   
        if([user_type isEqualToString:@"超级管理员"] || [user_type isEqualToString:@"物业管理员"] || [user_type isEqualToString:@"小区管理员"]){//boss 或者 物业管理员
            for(NSInteger index = 0;index<4; index++){
                UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%ld",(long)index+1]];
                NSString *title = NULL;
                
                if(index == 0){
                    title =  @"客户资料" ;
                    NSDictionary *dic = @{@"image": [UIImage imageNamed:[NSString stringWithFormat:@"%d",10]], @"title":title};
                    [self.dataMArr addObject:dic];
                } else if(index == 1){
                    title =  @"维修业务" ;
                    NSDictionary *dic = @{@"image": [UIImage imageNamed:[NSString stringWithFormat:@"%d",4]], @"title":title};
                    [self.dataMArr addObject:dic];
                } else if(index == 2){
                    title =  @"邻里小圈" ;
                    NSDictionary *dic = @{@"image": image, @"title":title};
                    [self.dataMArr addObject:dic];
                } else if(index == 3){
                    NSString *title = NULL;
                    title =  @"物业通知" ;
                    NSInteger index = 0;
                    UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%ld",(long)index+1]];
                    UIImage *image2 = [UIImage imageNamed:@"home_circle_tip.png"];
                    NSLog(@"@@@@@@@@@@%@",[data objectForKeyOrNil:@"resultinfo"]);
                    if([data objectForKeyOrNil:@"resultinfo"]==nil || [[data objectForKeyOrNil:@"resultinfo"] isEqualToString:@"0"]){
                        NSDictionary *dic2 = @{@"image": image, @"title":title};
                        [self.dataMArr addObject:dic2];
                    } else {
                        NSDictionary *dic = @{@"image": image,@"image2": image2,  @"title":title,@"title2":[data objectForKeyOrNil:@"resultinfo"]};
                        [self.dataMArr addObject:dic];
                    }
                }
            }

        } else if([user_type isEqualToString:@"客服管理员"] || [user_type isEqualToString:@"客服人员"]){ //客服
            for(NSInteger index = 0;index<4; index++){
                //UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%ld",(long)index+1]];
                NSString *title = NULL;
                
                if(index == 0){
                    title =  @"客户资料" ;
                    NSDictionary *dic = @{@"image": [UIImage imageNamed:[NSString stringWithFormat:@"%d",10]], @"title":title};
                    [self.dataMArr addObject:dic];
                } else if(index == 1){
                    title =  @"邻里小圈" ;
                    NSDictionary *dic = @{@"image": [UIImage imageNamed:[NSString stringWithFormat:@"%d",3]], @"title":title};
                    [self.dataMArr addObject:dic];
                } else if(index == 2){
                    NSString *title = NULL;
                    title =  @"物业通知" ;
                    UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%d",1]];
                    
                    UIImage *image2 = [UIImage imageNamed:@"home_circle_tip.png"];
                    
                    if([data objectForKeyOrNil:@"resultinfo"]==nil || [[data objectForKeyOrNil:@"resultinfo"] isEqualToString:@"0"]){
                        NSDictionary *dic2 = @{@"image": image, @"title":title};
                        [self.dataMArr addObject:dic2];
                    } else {
                        NSDictionary *dic = @{@"image": image,@"image2": image2,  @"title":title,@"title2":[data objectForKeyOrNil:@"resultinfo"]};
                        [self.dataMArr addObject:dic];
                    }

                }
            }

        } else if([user_type isEqualToString:@"维修管理员"] || [user_type isEqualToString:@"维修人员"]){//维修人员
            for(NSInteger index = 0;index<3; index++){
                NSString *title = NULL;
                
                if(index == 0){
                    title =  @"维修业务" ;
                    NSDictionary *dic = @{@"image": [UIImage imageNamed:[NSString stringWithFormat:@"%d",4]], @"title":title};
                    [self.dataMArr addObject:dic];
                } else if(index == 1){
                    title =  @"邻里小圈" ;
                    NSDictionary *dic = @{@"image": [UIImage imageNamed:[NSString stringWithFormat:@"%d",3]], @"title":title};
                    [self.dataMArr addObject:dic];

                } else if(index == 2){
                    NSString *title = NULL;
                    title =  @"物业通知" ;
                    UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%d",1]];
                    
                    UIImage *image2 = [UIImage imageNamed:@"home_circle_tip.png"];
                    
                    if([data objectForKeyOrNil:@"resultinfo"]==nil || [[data objectForKeyOrNil:@"resultinfo"] isEqualToString:@"0"]){
                        NSDictionary *dic2 = @{@"image": image, @"title":title};
                        [self.dataMArr addObject:dic2];
                    } else {
                        NSDictionary *dic = @{@"image": image,@"image2": image2,  @"title":title,@"title2":[data objectForKeyOrNil:@"resultinfo"]};
                        [self.dataMArr addObject:dic];
                    }

                }
            }

        } else if([user_type isEqualToString:@"财务管理员"] || [user_type isEqualToString:@"财务人员"]){ //财务
            
        }

        if ([[[UIDevice currentDevice] systemVersion] floatValue] <= 8.0) {
            _myConllection.frame  = CGRectMake(0, 230, self.view.frame.size.width, self.view.frame.size.height-70);
        }
        self.myConllection.delegate = self;
        self.myConllection.dataSource = self;
        
        
    }
    
}

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{

        TongzhiViewController *reportVC = (TongzhiViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"TongzhiViewController"];
        NSDictionary *wzInfo = [self.tzList objectAtIndex:index];
        NSLog(@"%@", self.tzList);
        reportVC.wzInfo = wzInfo;
        [self.navigationController pushViewController:reportVC animated:YES];
    
    
}

- (void)loadWeather
{
    
    NSError *error;
    
    NSURL *URL =[NSURL URLWithString:[@"http://weather.51wnl.com/weatherinfo/GetMoreWeather?cityCode=101190701&weatherType=0" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
    NSString *stringFromFileAtURL = [[NSString alloc]
                                     initWithContentsOfURL:URL
                                     encoding:NSUTF8StringEncoding
                                     error:&error];
    NSString *strTemp;
    NSString *date_y;
    NSString *strWeather;
    NSString *city;
    NSString *fileName=@"晴.png";
    
    if(stringFromFileAtURL !=nil)
    {
        
        NSArray *strarray = [stringFromFileAtURL componentsSeparatedByString:@"\""];
        
        for(int i=0;i<strarray.count;i++)
        {
            NSString *str = [strarray objectAtIndex:i];
            if(YES == [str isEqualToString:@"city"])//时间
            {
                city = [strarray objectAtIndex:i+2];
            }
            else if(YES == [str isEqualToString:@"date_y"])//时间
            {
                date_y = [strarray objectAtIndex:i+2];
            }
            else if(YES == [str isEqualToString:@"temp1"])//最低温度_最高温度
            {
                strTemp = [strarray objectAtIndex:i+2];
            }
            else if(YES == [str isEqualToString:@"weather1"])//天气
            {
                strWeather = [strarray objectAtIndex:i+2];
            }
            
        }
        self.cityText.text = city;
        self.dayText.text = date_y;
        self.wenduText.text = strTemp;
        NSString *sweather = [[NSString alloc]initWithFormat:@"%@",strWeather];
        if(NSNotFound != [strWeather rangeOfString:@"晴"].location)
        {
            fileName =[[NSString alloc]initWithFormat:@"%@",@"晴.png"];
        }
        if(NSNotFound != [strWeather rangeOfString:@"多云"].location)
        {
            fileName =[[NSString alloc]initWithFormat:@"%@", @"多云.png"];
        }
        if(NSNotFound != [strWeather rangeOfString:@"阴"].location)
        {
            fileName =[[NSString alloc]initWithFormat:@"%@", @"阴.png"];
        }
        if(NSNotFound != [strWeather rangeOfString:@"雨"].location)
        {
            fileName =[[NSString alloc]initWithFormat:@"%@", @"中雨.png"];
        }
        if(NSNotFound != [strWeather rangeOfString:@"雪"].location)
        {
            fileName =[[NSString alloc]initWithFormat:@"%@", @"小雪.png"];
        }
        if(NSNotFound != [strWeather rangeOfString:@"雷"].location)
        {
            fileName =[[NSString alloc]initWithFormat:@"%@", @"雷雨.png"];
        }
        if(NSNotFound != [strWeather rangeOfString:@"雾"].location)
        {
            fileName =[[NSString alloc]initWithFormat:@"%@", @"雾.png"];
        }
        if(NSNotFound != [strWeather rangeOfString:@"大雪"].location)
        {
            fileName =[[NSString alloc]initWithFormat:@"%@", @"大雪.png"];
        }
        if(NSNotFound != [strWeather rangeOfString:@"大雨"].location)
        {
            fileName =[[NSString alloc]initWithFormat:@"%@", @"大雨.png"];
        }
        if(NSNotFound != [strWeather rangeOfString:@"中雪"].location)
        {
            fileName = [[NSString alloc]initWithFormat:@"%@",@"中雪.png"];
        }
        if(NSNotFound != [strWeather rangeOfString:@"中雨"].location)
        {
            fileName = [[NSString alloc]initWithFormat:@"%@",@"中雨.png"];
        }
        if(NSNotFound != [strWeather rangeOfString:@"小雪"].location)
        {
            fileName = [[NSString alloc]initWithFormat:@"%@",@"小雪.png"];
        }
        if(NSNotFound != [strWeather rangeOfString:@"小雨"].location)
        {
            fileName = [[NSString alloc]initWithFormat:@"%@",@"中雨.png"];
        }
        if(NSNotFound != [strWeather rangeOfString:@"雨加雪"].location)
        {
            fileName =[[NSString alloc]initWithFormat:@"%@", @"雨夹雪.png"];
        }
        if(NSNotFound != [strWeather rangeOfString:@"阵雨"].location)
        {
            fileName =[[NSString alloc]initWithFormat:@"%@", @"中雨.png"];
        }
        if(NSNotFound != [strWeather rangeOfString:@"雷阵雨"].location)
        {
            fileName =[[NSString alloc]initWithFormat:@"%@", @"雷阵雨.png"];
        }
        if(NSNotFound != [strWeather rangeOfString:@"大雨转晴"].location)
        {
            fileName =[[NSString alloc]initWithFormat:@"%@", @"大雨转晴.png"];
        }
        if(NSNotFound != [strWeather rangeOfString:@"阴转晴"].location)
        {
            fileName =[[NSString alloc]initWithFormat:@"%@", @"阴转晴.png"];
        }
        
        if(sweather !=nil)
            self.weathText.text = sweather;
    }
    self.weathImage.image = [UIImage imageNamed:fileName];
    [self sendDeviceInfo];
}



-(void)setUpCollection{
    if (self.networkManager == nil) {
        self.networkManager = [[NetworkManager alloc] init];
    }
    NSString *user_id = [user.info objectForKey:@"id"];
    NSString *xiaoqu_id = @"8";
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           xiaoqu_id,@"xiaoqu_id", user_id,@"user_id",nil];
    [self.networkManager requestWithMethod:getUnreadCount parameter:param delegate:self];
    [self.HUD show:YES];
    
}

- (IBAction)grzlAction:(id)sender {
    GrzlViewController *problemVC = (GrzlViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"GrzlViewController"];
    [self.navigationController pushViewController:problemVC animated:YES];
}

#pragma mark - Collection View Data Source
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataMArr.count;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    CATransition* transition = [CATransition animation];
    transition.type = kCATransitionPush;//可更改为其他方式
    transition.subtype = kCATransitionFromLeft;//可更改为其他方式
    NSString *user_type = [user.info objectForKey:@"roleName"];
    if([user_type isEqualToString:@"超级管理员"] || [user_type isEqualToString:@"物业管理员"] || [user_type isEqualToString:@"小区管理员"]){//boss 或者 物业管理员

    if(indexPath.row == 0){
        KhzlViewController *problemVC = (KhzlViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"KhzlViewController"];
        [self.navigationController.view.layer addAnimation:transition forKey:kCATransition];
        [self.navigationController pushViewController:problemVC animated:YES];
       
    } else if(indexPath.row == 1){
        WeixListViewController *problemVC = (WeixListViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"WeixListViewController"];
        [self.navigationController.view.layer addAnimation:transition forKey:kCATransition];
        [self.navigationController pushViewController:problemVC animated:YES];
    } else if(indexPath.row == 2){
        
        WXViewController *wxVc = [WXViewController new];
        [self.navigationController.view.layer addAnimation:transition forKey:kCATransition];
        [self.navigationController pushViewController:wxVc animated:NO];
        
    } else if(indexPath.row == 3){
        TongzhiListViewController *problemVC = (TongzhiListViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"TongzhiListViewController"];
        [self.navigationController.view.layer addAnimation:transition forKey:kCATransition];
        [self.navigationController pushViewController:problemVC animated:NO];
        
    }
    } else if([user_type isEqualToString:@"客服管理员"] || [user_type isEqualToString:@"客服人员"]){ //客服
        if(indexPath.row == 0){
            KhzlViewController *problemVC = (KhzlViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"KhzlViewController"];
            [self.navigationController.view.layer addAnimation:transition forKey:kCATransition];
            [self.navigationController pushViewController:problemVC animated:YES];
            
        } else if(indexPath.row == 1){
            WXViewController *wxVc = [WXViewController new];
            [self.navigationController.view.layer addAnimation:transition forKey:kCATransition];
            [self.navigationController pushViewController:wxVc animated:NO];
        } else if(indexPath.row == 2){
            TongzhiListViewController *problemVC = (TongzhiListViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"TongzhiListViewController"];
            [self.navigationController.view.layer addAnimation:transition forKey:kCATransition];
            [self.navigationController pushViewController:problemVC animated:NO];
            
        }
    } else if([user_type isEqualToString:@"维修管理员"] || [user_type isEqualToString:@"维修人员"]){//维修人员
        if(indexPath.row == 0){
            WeixListViewController *problemVC = (WeixListViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"WeixListViewController"];
            [self.navigationController.view.layer addAnimation:transition forKey:kCATransition];
            [self.navigationController pushViewController:problemVC animated:YES];
        } else if(indexPath.row == 1){
            WXViewController *wxVc = [WXViewController new];
            [self.navigationController.view.layer addAnimation:transition forKey:kCATransition];
            [self.navigationController pushViewController:wxVc animated:NO];
        } else if(indexPath.row == 2){
            TongzhiListViewController *problemVC = (TongzhiListViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"TongzhiListViewController"];
            [self.navigationController.view.layer addAnimation:transition forKey:kCATransition];
            [self.navigationController pushViewController:problemVC animated:NO];
        }
    }
    return;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *collectionCellID = @"myCollectionCell";
    collectionCell *cell = (collectionCell *)[collectionView dequeueReusableCellWithReuseIdentifier:collectionCellID forIndexPath:indexPath];
    
    NSDictionary *dic    = self.dataMArr[indexPath.row];
    UIImage *image       = dic[@"image"];
    UIImage *image2       = dic[@"image2"];
    NSString *title      = dic[@"title"];
    NSString *title2      = dic[@"title2"];
    
    cell.imageView.image = image;
    cell.titleLabel.text = title;
    if(image2 != nil){
        cell.imageView2.hidden = false;
        cell.titleLabel2.hidden = false;
        cell.titleLabel2.text = title2;
    }
    
    return cell;
};

@end

